var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');

var readJson = require('./readJson');
// 要存入的内容
var filePath = path.join(__dirname,'..','public','liuyan.json');


/* GET home page. */
router.get('/', function(req, res, next) {
    res.locals.user = req.session.user || '';
    // fs.readFile(filePath,'utf-8',(err,data)=>{
    //     var dataString = '';
    //     if(data){
    //         dataString = '['+data.substring(0,data.length-1)+']';
    //     }else{
    //         dataString = '[{"nicheng":"郝多","con":"深刻感悟和把握马克思主义真理力量","time":"2018-04-24 20:30:40"}]';
    //         fs.writeFile(filePath,JSON.stringify(JSON.parse(dataString)[0])+',');
    //     }
    //     res.render('index', { list : dataString ? JSON.parse(dataString).reverse() : [] });
    // });
    readJson(filePath,function(dataString){
         res.render('index', { list : dataString ? JSON.parse(dataString).reverse() : [] });
    });
});

router.post('/addly',function(req,res,next){
    const {nicheng,con} = req.body;
    var now = new Date();
    var month = now.getMonth()+1;
    var date = now.getDate();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    // var time = now.getFullYear()+'-'+(now.getMonth()+1)+'-'+now.getDate()+' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
    var time = now.getFullYear()+'-'+addZero(month)+'-'+ addZero(date)+' '+addZero(hours)+':'+addZero(minutes)+':'+addZero(seconds);

    var responseJson = {nicheng,con,time};
    // 数据写入文件
    fs.appendFile(filePath,JSON.stringify(responseJson)+',');

    res.json(responseJson);
});


function addZero(number){
    return number<10 ? '0'+number : number;
}

module.exports = router;
